package com.android.baseconfig.data.http.okhttp.interceptor;

import android.content.Context;

import com.android.baseconfig.common.utils.Logc;
import com.android.baseconfig.data.http.AppNetDelegate;
import com.android.baseconfig.data.http.okhttp.util.NetworkUtil;

import java.io.IOException;

import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

public class HttpCacheInterceptor implements Interceptor {
    private Context context;

    public HttpCacheInterceptor() {
        context = AppNetDelegate.getAppContext();
    }

    public void setContext(Context context) {
        this.context = context;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        if (context != null && !NetworkUtil.isNetworkAvailable(context)) {
            request = request.newBuilder()
                    .cacheControl(CacheControl.FORCE_CACHE)
                    .build();
            Logc.d("Okhttp", "no network");
        }

        Response originalResponse = chain.proceed(request);
        if (context != null && NetworkUtil.isConnected(context)) {
            //有网的时候读接口上的@Headers里的配置，你可以在这里进行统一的设置
//                Response.Builder builder = originalResponse.newBuilder();
//                Response clone = builder.build();
//                ResponseBody body = clone.body();
//                System.out.println("uuok.base....:"+body.string());

            String cacheControl = request.cacheControl().toString();
            return originalResponse.newBuilder()
                    .header("Cache-Control", cacheControl)
                    .removeHeader("Pragma")
                    .build();
        } else {
            return originalResponse.newBuilder()
                    .header("Cache-Control", "public, only-if-cached, max-stale=2419200")
                    .removeHeader("Pragma")
                    .build();
        }
    }
}